package com.wcy.inteceptor;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import io.seata.core.context.RootContext;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Objects;

@Component
@Order(1)
public class FeignHeaderInteceptor implements RequestInterceptor {
    @Value("${security.internal.token-provider}")
    private String internalProviderGatewayToken;
    @Resource
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    public void apply(RequestTemplate template) {
        ServletRequestAttributes attributes = (ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes();
        assert attributes != null;
        String xid = RootContext.getXID();
        if (StringUtils.isNotBlank(xid)) {
            template.header(RootContext.KEY_XID, xid);
        }
        String authorization = attributes.getRequest().getHeader("Authorization");
        //获取当前的请求上下文的查询数据并转接给下游的provider服务
        template.header("X-Query-Data",attributes.getRequest().getHeader("X-Query-Data"));
        if(authorization!=null&&authorization.length()>7){
            String token = authorization.substring(7);
            if(Boolean.TRUE.equals(redisTemplate.hasKey(token)))
                template.header("X-Perms", Objects.requireNonNull(redisTemplate.opsForValue().get(token)).toString());
//            System.out.println(redisTemplate.opsForValue().get(token));
            template.header("Authorization",authorization);
        }
        //用于下游provider服务认证
        template.header("X-My-Consumer-Token", internalProviderGatewayToken);
    }
}
